package it.uniroma3.dia.ia.textcategorization.categorizer;

import it.uniroma3.dia.ia.textcategorization.model.Category;
import it.uniroma3.dia.ia.textcategorization.model.Text;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * Start point for a CategorizerBuilder implementation.
 * Optionally performs text preprocessing.
 * 
 * @author Marco Liceti
 *
 */
public abstract class BasicCategorizerBuilder implements CategorizerBuilder {

	protected TextPreprocessor preprocessor;

	@Override
	public Categorizer newCategorizer(Set<Category> categories,
			Map<Text, Category> trainingSet) {
		Map<Text, Category> preprocessedTrainingSet = prepare(trainingSet);
		Categorizer categorizer = build(categories, preprocessedTrainingSet);
		return categorizer;
	}

	/**
	 * Prepares the training set by preprocessing the Text
	 * instances that it contains.
	 * 
	 * @param trainingSet The training set.
	 * @return the preprocessed training set.
	 * 
	 */
	protected Map<Text, Category> prepare(Map<Text, Category> trainingSet) {
		if (this.preprocessor != null) {
			Map<Text, Category> preprocessedTrainingSet = new HashMap<Text, Category>();
			for (Text text : trainingSet.keySet()) {
				Text preprocessedText = this.preprocessor.preprocess(text);
				preprocessedTrainingSet.put(preprocessedText, trainingSet.get(text));
			}
			return preprocessedTrainingSet;
		} else return trainingSet;
	}

	/**
	 * 
	 * Performs the actual Categorizer construction.
	 * 
	 * @param categories The categories the Categorizer will work against. 
	 * @param preprocessedTrainingSet A preprocessed training set.
	 * @return the newly created Categorizer.
	 * 
	 */
	protected abstract Categorizer build(Set<Category> categories,
			Map<Text, Category> preprocessedTrainingSet);

}
